package 线程池;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * 线程池的4种创建方式
 * Created by huangyu on 2018/9/1 19:51
 */
public class ThreadPool {

	public static void main(String[] args) {
		// 创建一个可缓存线程池，如果线程池长度超过处理需要，可灵活回收空闲线程，若无可回收，则新建线程
		/*ExecutorService cachedThreadPool = Executors.newCachedThreadPool();
		for (int i = 0; i < 20; i++) {
			cachedThreadPool.execute(new Runnable() {
				@Override
				public void run() {
					System.out.println("ThreadName：" + Thread.currentThread().getName());
				}
			});
		}*/

		// 创建一个定长线程池，可控制线程最大并发数，超出的线程会在队列中等待
		/*ExecutorService fixedThreadPool = Executors.newFixedThreadPool(3);
		for (int i = 0; i < 5; i++) {
			fixedThreadPool.execute(new Runnable() {
				@Override
				public void run() {
					System.out.println("ThreadName：" + Thread.currentThread().getName());
				}
			});
		}*/

		// 创建一个定长线程池，支持定时及周期性任务执行。延迟执行
		/*ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(3);
		for (int i = 0; i < 10; i++) {
			final int temp = i;
			scheduledThreadPool.schedule(new Runnable() {
				public void run() {
					System.out.println(Thread.currentThread().getName() + " i:" + temp);
				}
			}, 3, TimeUnit.SECONDS);
		}*/

		ExecutorService newSingleThreadExecutor = Executors.newSingleThreadExecutor();
		for (int i = 0; i < 10; i++) {
			newSingleThreadExecutor.execute(new Runnable() {
				@Override
				public void run() {
					System.out.println(Thread.currentThread().getName());
					try {
						Thread.sleep(200);
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			});
		}

	}
}
